package com.topscomm.mpm.script;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import com.topscomm.basic.BasicEntity;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.service.impl.*;
import com.topscomm.tap.common.ParameterCache;
import org.springframework.transaction.annotation.Transactional;

import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.mpm.MpmScript;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.TapEntity;
import org.springframework.util.CollectionUtils;

public class MpmProjectTeamScript extends MpmScript {

	/**
	 * 任命审批结束后更新任命书和项目组成员信息和项目立项主表信息
	 * 同时将项目状态改为：策划阶段
	 * @param service
	 * @param entity
	 * @throws Exception
	 * @modify: liuchenguang 2021-8-11 增加相关方添加、更新、删除
	 */
	@Transactional
	public void projectTeamAfterApproval(ITapService service, TapEntity entity) throws Exception {
		// 审批节点实例
		CboApprovalNodeInsEntity nodeins = (CboApprovalNodeInsEntity) entity;
		String sourceid = ConvertUtil.convertToString(nodeins.getSourceid());
		MpmProjectAppointmentService mpmProjectAppointmentService = (MpmProjectAppointmentService) SpringUtil
			.getBean("mpmProjectAppointmentService");
		MpmProjectTeamService mpmProjectTeamService = (MpmProjectTeamService) SpringUtil
			.getBean("mpmProjectTeamService");
		MpmProjectService mpmProjectService = (MpmProjectService) SpringUtil
			.getBean("mpmProjectService");
		MpmProjectStakeholderService mpmProjectStakeholderService = (MpmProjectStakeholderService) SpringUtil
			.getBean("mpmProjectStakeholderService");
		MpmProjectTeamTypeService mpmProjectTeamTypeService = (MpmProjectTeamTypeService) SpringUtil.getBean("mpmProjectTeamTypeService");
		//更新任命书签发日期
		MpmProjectAppointmentEntity mpmProjectAppointmentEntity = mpmProjectAppointmentService.queryById(sourceid);
		mpmProjectAppointmentEntity.setSigndate(new Date());
		mpmProjectAppointmentService.updateEntity(mpmProjectAppointmentEntity);
		// 获取项目编号，任命书id
		String projectCode = mpmProjectAppointmentEntity.getProjectcode();
		String appointmentId = ConvertUtil.convertToString(mpmProjectAppointmentEntity.getId());
		//查询项目entity
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendLineSingle("projectcode = '{0}'", projectCode);
		List<MpmProjectEntity> mpmProjectEntities = mpmProjectService.queryByWhere(sql.toString());
		String sysPush = mpmProjectAppointmentEntity.getSyspush();
		// 首次任命时更新状态
		if(!CollectionUtils.isEmpty(mpmProjectEntities) && !StringUtil.isEmpty(sysPush) && sysPush.equals("1")){
			MpmProjectEntity mpmProjectEntity = mpmProjectEntities.get(0);
			//更新状态：策划状态（任命审批结束到策划审批结束）
			mpmProjectEntity.setSchedulestate(MpmSystemConst.MpmScheduleState.PlanState);
			mpmProjectEntity.setAppointmentenddate(new Date());
			mpmProjectService.updateEntity(mpmProjectEntity);
		}
		// 任命审批通过后给项目组表添加项目领导组成员
		if (MpmSystemConst.MPM_APPOINTMENT_SYSPUSH.equals(mpmProjectAppointmentEntity.getSyspush())) {
			long appointmentEntityId = mpmProjectAppointmentEntity.getId();
			insertTeam(appointmentEntityId, mpmProjectAppointmentEntity.getProjectmanagercode(), mpmProjectAppointmentEntity.getProjectmanager(),
					"项目领导组", MpmSystemConst.WorkGroupRoleCode.pm, projectCode, 0L);
			insertTeam(appointmentEntityId, mpmProjectAppointmentEntity.getSponsorcode(), mpmProjectAppointmentEntity.getSponsor(),
					"项目领导组", MpmSystemConst.WorkGroupRoleCode.sponsor, projectCode, 0L);
			insertTeam(appointmentEntityId, mpmProjectAppointmentEntity.getOwnercode(), mpmProjectAppointmentEntity.getOwner(),
					"项目领导组", MpmSystemConst.WorkGroupRoleCode.owner, projectCode, 0L);
			String adviserCode = mpmProjectAppointmentEntity.getAdvisercode();
			String adviser = mpmProjectAppointmentEntity.getAdviser();
			if (!StringUtil.isEmpty(adviser) && !StringUtil.isEmpty(adviserCode)) {
				insertTeam(appointmentEntityId, adviserCode, adviser, "项目领导组",
						"顾问", projectCode, 0L);
			}
		}

		// 获取项目组成员列表
		if (!StringUtil.isEmpty(appointmentId)) {
			StringBufferProxy whereSql = new StringBufferProxy();
			whereSql.appendLineSingle("appointmentid = '{0}'", appointmentId);
			List<MpmProjectTeamEntity> mpmProjectTeamEntities = mpmProjectTeamService.queryByWhere(whereSql.toString());
			//如果包含项目经理,Sponsor,Owner变更，则回写主表
			boolean isChangePmSpnsorOwner = false;
			// 根据任命or撤销，任命:回写字段，撤销:查询原有成员进行撤销操作并回写字段
			List<BasicEntity> stakeHolderEntities = new ArrayList<BasicEntity>();
			List<BasicEntity> teamEntities = new ArrayList<BasicEntity>();
			List<BasicEntity> projectEntities = new ArrayList<BasicEntity>();
			// 如果项目组中存在固定项目组，则在相关方中将项目核心组的enabled值置为0
			List<MpmProjectTeamTypeEntity> mpmProjectTeamTypeEntities = mpmProjectTeamTypeService.queryByWhere(whereSql.toString());
			boolean deleteFlag = false;
			for (MpmProjectTeamTypeEntity mpmProjectTeamTypeEntity : mpmProjectTeamTypeEntities) {
				if (mpmProjectTeamTypeEntity.getGrouptype() > 0) {
					deleteFlag = true;
					break;
				}
			}
			if (deleteFlag && !CollectionUtil.isEmpty(mpmProjectTeamEntities)) {
				whereSql.clear();
				whereSql.appendSingle(" projectcode = '{0}' and message = '{1}' and enabled = 1 ",
						mpmProjectTeamEntities.get(0).getProjectcode(), MpmSystemConst.ProjectCoreTeamType);
				List<MpmProjectStakeholderEntity> mpmProjectStakeholderEntities = mpmProjectStakeholderService.queryByWhere(whereSql.toString());
				List<BasicEntity> resultEntities = new ArrayList<BasicEntity>();
				for (MpmProjectStakeholderEntity thisEntity : mpmProjectStakeholderEntities) {
					// 有效值设置为0
					thisEntity.setEnabled(0);
					resultEntities.add(thisEntity);
				}
				mpmProjectStakeholderService.updateBatch(resultEntities);
			}
			for (MpmProjectTeamEntity mpmProjectTeamEntity : mpmProjectTeamEntities) {
				// 9已审核，项目组成员状态和主表state保持一致
				mpmProjectTeamEntity.setState(9);
				String appointmentType = mpmProjectTeamEntity.getAppointmenttype();
				// 1任命，2撤销
				if ("1".equals(appointmentType)) {
					mpmProjectTeamEntity.setAppointdate(new Date());
					teamEntities.add(mpmProjectTeamEntity);
					// 添加相关方人员
					String roleCode = mpmProjectTeamEntity.getProjectrole();
					if(mpmProjectStakeholderService.isCenter(roleCode)) {
						// 添加项目组成员
						MpmProjectStakeholderEntity stakeholderEntity = mpmProjectStakeholderService
								.addStakeholderInfo(mpmProjectTeamEntity);
						if (stakeholderEntity != null) {
							stakeHolderEntities.add(stakeholderEntity);
						}
					}
				} else if ("2".equals(appointmentType)) {
					mpmProjectTeamEntity.setRevokedate(new Date());
					teamEntities.add(mpmProjectTeamEntity);
					String revokeUsercode = mpmProjectTeamEntity.getUsercode();
					String projectCodeFromTeam = mpmProjectTeamEntity.getProjectcode();
					String projectRole = mpmProjectTeamEntity.getProjectrole();
					String workGroup = mpmProjectTeamEntity.getWorkgroup();
					whereSql.clear();
					whereSql.appendSingle(
						"usercode = '{0}' and projectcode = '{1}' and projectrole = '{2}' "
							+ "and workgroup = '{3}' and appointmenttype = '1' and enabled = 1 ",
						revokeUsercode, projectCodeFromTeam, projectRole, workGroup);
					List<MpmProjectTeamEntity> mpmProjectTeamEntities2 = mpmProjectTeamService
						.queryByWhere(whereSql.toString());
					if (!mpmProjectTeamEntities2.isEmpty()) {
						MpmProjectTeamEntity mpmProjectTeamEntity2 = mpmProjectTeamEntities2.get(0);
						mpmProjectTeamEntity2.setEnabled(0);
						mpmProjectTeamService.updateEntity(mpmProjectTeamEntity2);
						// 撤销相关方人员
						String roleCode = mpmProjectTeamEntity.getProjectrole();
						if(mpmProjectStakeholderService.isCenter(roleCode)) {
							// 撤销相关方表中人员，领导组人员不撤销
							mpmProjectStakeholderService.revokeStakeholderInfo(mpmProjectTeamEntities2.get(0));
						}
					}
				}
				// 判断项目主表是否经过变更
				if("pm".equals(mpmProjectTeamEntity.getProjectrole()) && "1".equals(appointmentType)) {
					if(!mpmProjectEntities.isEmpty()) {
						MpmProjectEntity mpmProjectEntity=mpmProjectEntities.get(0);
						mpmProjectEntity.setProjectmanagercode(mpmProjectTeamEntity.getUsercode());
						mpmProjectEntity.setProjectmanager(mpmProjectTeamEntity.getUsername());
						projectEntities.add(mpmProjectEntity);
						isChangePmSpnsorOwner =true;
					}
				}
				if("sponsor".equals(mpmProjectTeamEntity.getProjectrole()) && "1".equals(appointmentType)) {
					if(!mpmProjectEntities.isEmpty()) {
						MpmProjectEntity mpmProjectEntity=mpmProjectEntities.get(0);
						mpmProjectEntity.setSponsorcode(mpmProjectTeamEntity.getUsercode());
						mpmProjectEntity.setSponsor(mpmProjectTeamEntity.getUsername());
						projectEntities.add(mpmProjectEntity);
						isChangePmSpnsorOwner =true;
					}
				}
				if("owner".equals(mpmProjectTeamEntity.getProjectrole()) && "1".equals(appointmentType)) {
					if(!mpmProjectEntities.isEmpty()) {
						MpmProjectEntity mpmProjectEntity=mpmProjectEntities.get(0);
						mpmProjectEntity.setOwnercode(mpmProjectTeamEntity.getUsercode());
						mpmProjectEntity.setOwner(mpmProjectTeamEntity.getUsername());
						projectEntities.add(mpmProjectEntity);
						isChangePmSpnsorOwner =true;
					}
				}
			}
			// 批量插入相关方表，批量更新项目组成员表、项目表
			if (!stakeHolderEntities.isEmpty()) {
				mpmProjectStakeholderService.insertBatch(stakeHolderEntities);
			}
			mpmProjectTeamService.updateBatch(teamEntities);
			if (!projectEntities.isEmpty()) {
				mpmProjectService.updateBatch(projectEntities);
			}
			// 更新相关方表
			if (isChangePmSpnsorOwner) {
				MpmProjectEntity mpmProjectEntity=mpmProjectEntities.get(0);
				mpmProjectStakeholderService.addProjectLeaderInfo(mpmProjectEntity.getProjectcode());
			}
		}
	}
	/**
	 * @param
	 * @param appointmentid
	 * @param usercode
	 * @param username
	 * @param workgroup
	 * @param projectrole
	 * @return
	 * @Title: insertTeam
	 * @description:插入项目组成员
	 * @author: lanjianwei
	 * @date: 2021年1月16日下午5:32:57
	 * @modify:
	 */
	private void insertTeam(long appointmentid, String usercode, String username, String workgroup, String projectrole,
			String projectcode, Long teamId) {
		MpmProjectTeamService mpmProjectTeamService = (MpmProjectTeamService) SpringUtil
				.getBean("mpmProjectTeamService");
		MpmProjectTeamEntity mpmProjectTeamEntity = new MpmProjectTeamEntity();
		mpmProjectTeamEntity.setProjectcode(projectcode);
		mpmProjectTeamEntity.setProjectrole(projectrole);
		mpmProjectTeamEntity.setWorkgroup(workgroup);
		mpmProjectTeamEntity.setUsercode(usercode);
		mpmProjectTeamEntity.setUsername(username);
		mpmProjectTeamEntity.setAppointmenttype("1");
		mpmProjectTeamEntity.setAppointmentid(appointmentid);
		mpmProjectTeamEntity.setAppointdate(new Date());
		mpmProjectTeamEntity.setState(1);
		mpmProjectTeamEntity.setTeamid(teamId);
		String mpm_leaderDuty = ParameterCache.getValue("Mpm_LeaderDuty");
		String[] split = mpm_leaderDuty.split("。");
		if ("pm".equals(projectrole)) {
			mpmProjectTeamEntity.setDuty(split[2]);
		} else if ("sponsor".equals(projectrole)) {
			mpmProjectTeamEntity.setDuty(split[0]);
		} else {
			mpmProjectTeamEntity.setDuty(split[1]);
		}
		mpmProjectTeamService.insert(mpmProjectTeamEntity);
	}
}
